package qnb.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import qnb._common.easyui.EasyuiGridData;
import qnb._common.easyui.EasyuiPageVO;
import qnb.dao.NafeMapper;
import qnb.entity.Nafe;
import qnb.entity.NafeExample;
import qnb.service.NafeService;

import java.util.List;

/**
 * @author huangxin
 * @date 2019/4/24-0:54
 */
@Service
@Qualifier("nafeService")
public class NafeServiceImpl implements NafeService {
    @Autowired
    private NafeMapper nafeMapper;

    @Override
    public EasyuiGridData listByPage(Nafe nafe, EasyuiPageVO vo) {
        NafeExample example = new NafeExample();
        NafeExample.Criteria criteria = example.createCriteria();

        //判断搜索属性
        if (StringUtils.isNotBlank(nafe.getNafeGrade())) {
            criteria.andNafeGradeLike("%" + nafe.getNafeGrade() + "%");
        }
        if (nafe.getStudentId()!=null) {
            criteria.andStudentIdEqualTo(nafe.getStudentId());
        }
        //设置排序
        if (StringUtils.isNotBlank(vo.getSort())) {
            String sort = toUnderScoreCase(vo.getSort());
            example.setOrderByClause(sort + " " + vo.getOrder());
        }


        //分页
        if (vo.getRows() > 0) {
            PageHelper.startPage(vo.getPage(), vo.getRows());
        }

        //查询
        List<Nafe> list = nafeMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
//            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Nafe> info = new PageInfo<>(list);
        return EasyuiGridData.getEasyuiGridData((int) info.getTotal(), list);
    }

    /**
     * 驼峰命名转下划线命名
     *
     * @param str
     * @return
     */
    public String toUnderScoreCase(String str) {
        String[] strings = StringUtils.splitByCharacterTypeCamelCase(str);
        for (int i = 0; i < strings.length; i++) {
            strings[i] = strings[i].toLowerCase();
        }
        return StringUtils.join(strings, "_");
    }


    @Override
    public int add(Nafe nafe) {
        return nafeMapper.insertSelective(nafe);
    }

    @Override
    public int update(Nafe nafe) {
        return nafeMapper.updateByPrimaryKeySelective(nafe);
    }

    @Override
    public int delete(Integer id) {
        return nafeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Nafe get(Integer id) {
        return nafeMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        return nafeMapper.deleteByIds(ids);
    }
}
